<template>
  <div class="image-upload-box">
    <el-upload
      :class="{ 'image-upload': fileList.length>0&&isShow }"
      action="#"
      list-type="picture-card"
      :http-request="updateFn"
      :file-list="fileList"
      :limit="4"
      :on-remove="removeFn"
    >
      <i class="el-icon-plus" />
    </el-upload>
    <el-progress v-if="percent>0&&percent<100" type="circle" :percentage="percent" status="success" />
  </div>
</template>

<script>
import COS from 'cos-js-sdk-v5'
// SECRETID 和 SECRETKEY请登录 https://console.cloud.tencent.com/cam/capi 进行查看和管理
// 初始化cos对象
var cos = new COS({
  SecretId: 'AKIDjZKtHTRAgEj28FGCd4NlsvqYLyZeXCcy',
  SecretKey: 'PhqqdBd1BKPOBWtCJG8tSrERRQM6ndO2'
})
export default {
  props: {
    isShow: {
      type: Boolean,
      default: true
    }
  },
  data() {
    return {
      fileList: [],
      percent: 0,
      imgUrl: ''
    }
  },

  methods: {
    removeFn() {
      this.fileList = []
    },
    updateFn(data) {
      console.log(data)
      this.imgUrl = data.imgUrl
      // this.fileList = [{ url: '' }]
      cos.uploadFile({
        Bucket: 'liuxin-1314796726', /* 填写自己的bucket，必须字段 */
        Region: 'ap-guangzhou', /* 存储桶所在地域，必须字段 */
        Key: Date.now().toString(), /* 存储在桶里的对象键（例如:1.jpg，a/b/test.txt，图片.jpg）支持中文，必须字段 */
        Body: data.file, // 上传文件对象
        onProgress: (progressData) => {
          this.percent = progressData.percent * 100
        },
        SliceSize: 1024 * 1024 * 5 /* 触发分块上传的阈值，超过5MB使用分块上传，小于5MB使用简单上传。可自行设置，非必须 */
      }, (err, data) => {
        if (err) {
          console.log('上传失败', err)
        } else {
          // this.fileList[0].url = 'https://' + data.Location
          this.fileList.push({ url: 'https://' + data.Location })
          console.log('上传成功', data)
          console.log('上传成功', this.fileList)
        }
      })
    }

  }

}
</script>

<style lang="scss">
.image-upload-box{
    display: inline-block;
    position: relative;
    .el-progress{
      position: absolute;
      top: 50%;
      left: 50%;
      transform: translate(-50%,-50%);
    }
}
.image-upload{
  .el-upload--picture-card{
        display: none;
    }
}
</style>
